package com.note.config.constants.filter;


import cn.hutool.core.text.AntPathMatcher;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.note.config.constants.constants.GatewayConstants;
import com.note.config.constants.vo.ResponseVo;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Package：com.note.gateway.annotation
 * @Name：GatewayFilter
 * @Author：热伊木
 * @Email：uyevan@163.com
 * @Date：2023-12-24-14:46
 * @Description：拦截器实现类
 */

@Slf4j
/*为了防止直接访问模块接口,需要检验的路由*/
/*urlPatterns --- 仅对此路径验证*/
@WebFilter(filterName = "gatewayFilter", urlPatterns = {"/user/*", "/note/*", "/share/*"}/*配置此路由规则还是无效，待解决*/)
public class GatewayFilter implements Filter {

    /*hutool字符匹配*/
    private final AntPathMatcher matcher = new AntPathMatcher();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    /*判断路由是否为模块间调用*/
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        /*如果在白名单则不验证*/
        if (pathPatterns(request)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        String gatewayKey = request.getHeader(GatewayConstants.GATEWAY_KEY_NAME);
        if (!StringUtils.hasLength(gatewayKey) || !gatewayKey.equals(GatewayConstants.GATEWAY_KEY)) {
            /*log.error("gateway key:{}", gatewayKey);*/
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.setContentType("application/json;charset=UTF-8");
            ResponseVo<String> responseVo = new ResponseVo<>(-1, false, "授权失败,请重试");
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonResponse = objectMapper.writeValueAsString(responseVo);
            PrintWriter out = response.getWriter();
            out.print(jsonResponse);
            out.flush();
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    /*路径匹配*/
    private boolean pathPatterns(HttpServletRequest request) {
        String path = request.getRequestURI();
        log.error("configPath:{}", path);
        /*是否无需拦截*/
        boolean isMatcher = false;
        for (String pattern : GatewayConstants.SERVER_DONT_PATH_PATTERNS) {
            if (matcher.match(pattern, path)) {
                isMatcher = true;
                break;
            }
        }
        return isMatcher;
    }
}
